package com.mk.cloud.common.controller;

import act.apidoc.Description;
import act.controller.Controller;
import act.inject.DefaultValue;
import act.validation.NotBlank;
import com.mk.cloud.common.domain.CpRoleUser;
import com.mk.cloud.common.domain.CpSsorole;
import com.mk.cloud.common.domain.CpSsorolePlatform;
import com.mk.cloud.common.domain.CpUser;
import com.mk.cloud.common.enums.ErrorCode;
import com.mk.cloud.common.enums.GlobalValues;
import com.mk.cloud.common.exception.UserException;
import com.mk.cloud.common.interceptor.ITransacte;
import com.mk.cloud.common.interceptor.cookie.CookieService;
import com.mk.cloud.common.interceptor.cookie.ICLogin;
import com.mk.cloud.common.msg.M;
import com.mk.cloud.common.msg.template.MsResetUserPwd;
import com.mk.cloud.common.util.CookieUtil;
import com.mk.cloud.common.util.DateUtils;
import com.mk.cloud.common.util.EncyUtils;
import org.osgl.util.S;import com.mk.cloud.common.util.S2;
import com.mk.cloud.pt.dto.CpUserDTO;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.osgl.http.H;
import org.osgl.mvc.annotation.*;
import org.osgl.mvc.result.Result;
import org.osgl.util.C;

import javax.inject.Inject;
import javax.validation.constraints.NotNull;
import java.util.*;

@Controller("user")
public class CpUserController extends CookieService {

    @Inject
    private CpUser.Mapper cpUserMapper;
    @Inject
    private CpSsorole.Mapper cpSsoroleMapper;
    @Inject
    private CpRoleUser.Mapper cpRoleUserMapper;
    @Inject
    private CpSsorolePlatform.Mapper cpSsorolePlatformMapper;

    @Description("*通用-员工-查询当前用户所在机构的所有员工列表(已实现)")
    @With(ICLogin.class)
    @GetAction("pageUsers.json")
    public PageQuery<CpUserDTO> cpUserList(
            @Description("筛选条件-姓名") String realname,
            @Description("筛选条件-手机号") String phone,
            @Description("获取公司员工时传入公司id")String coid,
            @Description("当前第几页") @NotNull Integer currentPage,
            @Description("每页多少条") @DefaultValue("15") Integer pageSize

    ){
        String sqlid = "cpUser.select_list_usertype0";
        String thrid = me.getThrid();
        PageQuery<CpUserDTO> query = new PageQuery<>();
        query.setPageSize(pageSize);
        query.setPageNumber(currentPage);
        Map<String,Object> map = new HashMap<>();
        map.put("thrid",thrid);
        map.put("realname",realname);
        map.put("phone",phone);
        if(S.isBlank(coid)){
            coid = me.getCoid();
        }
        map.put("coid",coid);
        query.setParas(map);
        //此处的sql是三个sql
        cpUserMapper.getSQLManager().pageQuery(sqlid,CpUserDTO.class,query);
        return query;
    }


    @Description("*通用-员工-增加, 返回cpuser成功 其它错误失败")
    @PostAction("add.json")
    @With({ICLogin.class, ITransacte.class })
    public CpUser add(@NotNull @Description("用于保存的对象") CpUser cpUser,@Description("角色id") String roleid) {
        validateUser(cpUser,true);
        String pwd = S.isBlank(cpUser.getPassword())?GlobalValues.DEFAULT_PASSWORD.value():cpUser.getPassword();
        cpUser.setPassword(EncyUtils.MD5(pwd));
        String userid = S2.UUID();
        cpUser.setUserid(userid);
        cpUser.setRegtime(DateUtils.getTimeNow());
        cpUserMapper.insert(cpUser);
        if(S.isNotBlank(roleid)){
            if(cpUser.getRoleids()!=null){
                cpUser.getRoleids().add(roleid);
            }else {
                List<String> roleids = new ArrayList<>();
                roleids.add(roleid);
                cpUser.setRoleids(roleids);
            }
        }
        saveRole(cpUser);

        if (S.isNotBlank(cpUser.getPhone())) {
            if (GlobalValues.COMMON_1.eq(cpUser.getUserstate())) {
//                M.excute(new MsAdminAddUser() {
//                    @Override public String username() {
//                        return cpUser.getPhone();
//                    }
//
//                    @Override public String password() {
//                        return pwd;
//                    }
//
//                    @Override public String phone() {
//                        return cpUser.getPhone();
//                    }
//                });
            }
        }
        return cpUser;
    }

    @Description("*通用-员工-查询当前用户所在机构的所有员工列表(已实现)")
    @With(ICLogin.class)
    @GetAction("cpRoleidList.json")
    public CpSsorolePlatform cpRoleidList(String userid){
        CpSsorolePlatform cpSsorolePlatform = new CpSsorolePlatform();
        List<String> roleids = cpUserMapper.getRoleidList(userid);
        if(roleids != null && roleids.size()>0){
            String roleid =roleids.get(0);
            cpSsorolePlatform = cpSsorolePlatformMapper.single(roleid);
        }
        return cpSsorolePlatform;
    }

    @Description("*通用-员工-修改, 返回1成功 其它错误失败")
    @PutAction("update.json")
    @With({ICLogin.class, ITransacte.class })
    public  Integer update(@NotNull @Description("用于修改的对象") CpUser cpUser,@Description("角色id")String roleid) {
        validateUser(cpUser,false);
        int updateCount = cpUserMapper.updateTemplateById(cpUser);
        if(S.isNotBlank(roleid)){
            if(cpUser.getRoleids()!=null){
                cpUser.getRoleids().add(roleid);
            }else {
                List<String> roleids = new ArrayList<>();
                roleids.add(roleid);
                cpUser.setRoleids(roleids);
            }
        }
        saveRole(cpUser);

        return updateCount;
    }

    @Description("*通用-员工-删除，返回1成功 其它错误失败，逻辑删除")
    @DeleteAction("{userid}/del.json")
    @With({ICLogin.class, ITransacte.class })
    public Integer del(@NotBlank  @Description("员工ID") String userid) {
        CpUser cpUser = new CpUser();
        cpUser.setUserid(userid);
        cpUserMapper.templateOne(cpUser);

        //验证是否管理员
        validateIsAdmin(cpUser);

        //验证是否是自己
        validateIsSelf(cpUser);

        //更改状态为冻结
        cpUser.setUserstate(GlobalValues.COMMON_0.value());
        return cpUserMapper.updateById(cpUser);
    }

    @Description("验证是否是自己")
    private void validateIsSelf(CpUser cpUser) {
        UserException.throwIf(me.getUserid().equals(cpUser.getUserid()), ErrorCode.E201011);
	}


	@Description("验证是否管理员")
    private void validateIsAdmin(CpUser cpUser) {
        List<CpSsorole> roleList = cpSsoroleMapper.getRolesByUser(cpUser.getUserid());
        for(int i=0;i<roleList.size();i++) {
            CpSsorole role = roleList.get(i);
            UserException.throwIf(role.getIsadmin().equals(GlobalValues.COMMON_1.value()), ErrorCode.E201012);
        }
    }

    /**
     * 自己修改密码
     */
    @PostAction("updatepwd.json")
    @With({ICLogin.class, ITransacte.class})
    @Description("通用-修改密码-通过验证旧密码，从而修改新密码")
    public int updatePwd(
            @NotBlank(message = "没有输入旧密码!") String oldpwd,
            @NotBlank(message = "没有输入新密码!") String newpwd
    ) {

        UserException.throwIf(S.isNotBlank(cpUserMapper.checkUserPwd(me.getUserid(),EncyUtils.MD5(oldpwd))),ErrorCode.E201008);
        return cpUserMapper.resetPwd(me.getUserid(),EncyUtils.MD5(newpwd));
    }

    /**
     * 自己修改密码-通过短信验证码
     */
    @PostAction("updatepwdbymscode.json")
    @With({ICLogin.class, ITransacte.class})
    @Description("通用-修改密码-通过短信验证码，从而修改新密码")
    public int updatePwdByMscode(
            CpUser user,
//            @NotBlank(message = "没有输入手机验证码") String msgcode,
            @Description("旧密码") String oldpassword
    ) {
        CpUser cpUser = cpUserMapper.single(me.getUserid());
        if(!S.eq(cpUser.getPassword(),EncyUtils.MD5(oldpassword))){
            UserException.throwNow(ErrorCode.E201008);
        }
        //旧密码验证通过通过
        user.setUserid(me.getUserid());
        if(S.isNotBlank(user.getPassword())){
            user.setPassword(EncyUtils.MD5(user.getPassword()));
        }
        cpUserMapper.updateTemplateById(user);
//        String cachedCode = CookieUtil.getCookie(GlobalValues.SMS_CODE.value() + "-" + user.getPhone(),context);
//        if(S.eq(cachedCode, msgcode)){
//            CpUser cpUser = new CpUser();
//            cpUser.setUserid(me.getUserid());
//            if(StringUtils.isNotBlank(password)) {
//                cpUser.setPassword(EncyUtils.MD5(password));
//                return cpUserMapper.updateTemplateById(cpUser);
//            } else {
//                return 0;
//            }
//        }else {
//            UserException.throwNow(ErrorCode.E201009);
//        }
        return 0;
    }


    /**
     * 修改用户信息-通过短信验证码
     */
    @PostAction("updateinfobymscode.json")
    @With({ICLogin.class, ITransacte.class})
    @Description("通用-修改用户信息-通过短信验证码")
    public int updateinfobymscode(CpUser user,
                                 @NotBlank(message = "没有输入手机验证码") String msgcode
    ) {
        CpUser userServer = cpUserMapper.single(me.getUserid());
        String cachedCode = CookieUtil.getCookie(GlobalValues.SMS_CODE.value() + "-" + userServer.getPhone(),context);
        if(S.eq(cachedCode, msgcode)){
            CpUser cpUser = new CpUser();
            cpUser.setUserid(me.getUserid());
            if(StringUtils.isNotBlank(user.getPassword())) {
                cpUser.setPassword(EncyUtils.MD5(user.getPassword()));
            }
            cpUser.setRealname(user.getRealname());
            return cpUserMapper.updateTemplateById(cpUser);
        }else {
            UserException.throwNow(ErrorCode.E201009);
        }
        return 0;
    }


    @Description("管理员帮自己的员工重置密码.暂时不要该功能(已实现)")
    @With({ICLogin.class, ITransacte.class})
    @PutAction("resetPwd.json")
    public int resetPwd(
            @Description("重置密码的用户id")
            @NotBlank String userid,
            @Description("要重置的密码")
            @NotBlank String password
    ){
        return cpUserMapper.resetPwd(userid, EncyUtils.MD5(password));
    }


    //用户增加或修改时验证方法
    private void validateUser(CpUser cpUser,Boolean isAdd) {
        if (S.isBlank(cpUser.getUserstate())) {
            cpUser.setUserstate(GlobalValues.COMMON_1.value());
        }
        CpUser example = new CpUser();
        CpUser check;
        List<String> errors = new ArrayList<>();
        if(S.isNotBlank(cpUser.getPhone())){
            try {
                example.setPhone(cpUser.getPhone());
                check = cpUserMapper.templateOne(example);
                example.setPhone(null);
                if ((isAdd && check != null) || (!isAdd && check != null && !Objects.equals(check.getUserid(), cpUser.getUserid()))) {
                    errors.add("手机号码重复");
                }
            } catch (Exception e) {
                errors.add("手机号码重复");
            }
        }
        //验证用户名不重复,(验证用户名必须包含字母)
        if(S.isNotBlank(cpUser.getUsername())){
            example.setUsername(cpUser.getUsername());
            try {
                check = cpUserMapper.templateOne(example);
                example.setUsername(null);
                if ((isAdd && check != null) || (!isAdd && check != null && !Objects.equals(check.getUserid(), cpUser.getUserid()))) {
                    errors.add("用户名重复");
                }
            } catch (Exception e) {
                errors.add("用户名重复");
            }
        }
        if(S.isNotBlank(cpUser.getEmail())){
            example.setEmail(cpUser.getEmail());
            try {
                check = cpUserMapper.templateOne(example);
                example.setEmail(null);
                if ((isAdd && check != null) || (!isAdd && check != null && !Objects.equals(check.getUserid(), cpUser.getUserid()))) {
                    errors.add("邮箱重复");
                }
            } catch (Exception e) {
                errors.add("邮箱重复");
            }
        }
        UserException.throwIf(!errors.isEmpty(), String.join(",",errors));
    }

    //用户增加和修改执行完后，保存角色
    private void saveRole(CpUser cpUser) {
        if (cpUser.getRoleids() == null) {
            cpUser.setRoleids(new ArrayList<>());
        }
        cpRoleUserMapper.saveUserRoles(cpUser.getRoleids(), cpUser.getUserid());
    }

/******* 未使用的功能 *******/


//    @GetAction({"{type}/index.html"})

    public Result index(String type) {
        if (S.isBlank(type)) type = "x";
        return render(type);
    }

    /**
     * 展示表单
     *
     * @param userid
     * @return
     */
//    @GetAction("form.html")

    public Result form(@NotBlank String userid) {
        boolean isAdd = S.isBlank(userid);
        CpUser cpUser;
        if (isAdd) {
            cpUser = new CpUser();
            cpUser.setUserstate(GlobalValues.COMMON_1.value());
            cpUser.setUsertype(GlobalValues.USERTYPE_0.value());
        } else {
            cpUser = cpUserMapper.unique(userid);
            List<String> roleids = cpUserMapper.getSQLManager().select("user.select_roleids", String.class, C.Map("userid", userid));
            cpUser.setRoleids(roleids);
        }
        List<CpSsorole> roles = cpSsoroleMapper.all();
        return null;
    }







    @PostAction("reset_pwd_by_admin.json")
    @With({ICLogin.class, ITransacte.class})
    @Description("重置密码")
    public Result reset_pwd_by_admin(@NotNull(message = "请指定用户") String userid) {
        CpUser user = new CpUser();
        user.setUserid(userid);
        String pwd = S2.randomNumberString(6);
        user.setPassword(EncyUtils.MD5(pwd));
        cpUserMapper.updateTemplateById(user);
        M.excute(new MsResetUserPwd() {
            @Override public String userId() {
                return user.getUserid();
            }

            @Override public String pwd() {
                return pwd;
            }
        });
        return ok();
    }


    /**
     * 个人信息页面
     *
     * @return
     */
//    @GetAction("info.html")
    @With({ICLogin.class})
    public void personInfo() {
    }

    /**
     * 个人信息存储
     *
     * @param session
     * @param realname
     * @param newPassword
     * @param password
     * @return
     */
    @PostAction("saveInfo.json")
    @With({ICLogin.class, ITransacte.class})
    @ResponseStatus(200)
    public Result savePersonInfo(H.Session session, String realname, String newPassword, String password) {
        CpUser user = session.cached("user");
        String userid = "";//cpUserMapper.getSQLManager().intValue("user.check_user_pwd", C.Map("userid", user.getUserid(), "password", EncyUtils.MD5(password)));
        UserException.throwIf(userid == null, "原密码错误!");
        CpUser cpUser = new CpUser();
        cpUser.setUserid(userid);
        boolean c = false;
        if (S.isNotBlank(realname)) {
            c = true;
            cpUser.setRealname(realname);
        }
        if (S.isNotBlank(newPassword)) {
            c = true;
            cpUser.setPassword(EncyUtils.MD5(newPassword));
        }
        if (c) {
            cpUserMapper.updateTemplateById(cpUser);
        }
        return render("/util/success.html");
    }



    @Description("通过手机号验证用户是否存在")
    public Boolean userExistByPhone(String phoneNum) {
        String t = cpUserMapper.selectUserByPhone(phoneNum);
        if(StringUtils.isNotBlank(t)) {
            return false;
        } else {
            return true;
        }
    }
}
